package com.glela.statistics.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.glela.platform.mapper.BaseRestrictionsMapper;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.VisitorRecordMapper;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.VisitorRecord;
import com.glela.statistics.mapper.OrderStatisticsMapper;
import com.glela.statistics.model.CommissionReport;
import com.glela.statistics.model.OrderReport;
import com.glela.statistics.model.SalesAmountReport;
import com.glela.statistics.model.SalesMonthReport;
import com.glela.statistics.model.StatisticsConstant;
import com.glela.statistics.model.TalentOrderEntity;
import com.glela.statistics.model.TalentOrderQuantityReport;
import com.glela.statistics.model.TalentStudent;
import com.glela.statistics.model.request.StoreCenterRequest;
import com.glela.statistics.model.response.ResponseWallet;
import com.glela.statistics.model.response.RevenueResponse;
import com.glela.statistics.model.response.SalesRanking;
import com.glela.statistics.model.response.StatisticsResponse;
import com.glela.statistics.model.response.StoreCenterOrderResponse;
import com.glela.statistics.model.response.TalentOrder;
import com.glela.statistics.model.response.TalentOrderDetail;
import com.glela.statistics.model.response.ThisMonthAchievement;
import com.glela.statistics.service.StatisticsService;

/**
 * 统计相关
 * 
 * @author 卫耀华
 *
 */
public abstract class AbstractStatisticsServiceImpl implements StatisticsService {

	private static Logger logger = LoggerFactory.getLogger(AbstractStatisticsServiceImpl.class);

	@Autowired
	private VisitorRecordMapper visitorRecordMapper;

	@Autowired
	private OrderStatisticsMapper orderStatisticsMapper;

	@Autowired
	private UserInfoMapper userInfoMapper;
	
	@Autowired
	private BaseRestrictionsMapper baseRestrictionsMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	/**
	 * 获取店铺7天30天90天统计（校妆APP3.5期需求）
	 * 
	 * @author 卫耀华
	 * @param userId
	 *            店主ID
	 * @param statisticsType
	 *            要统计的类型
	 * @param dayNumType
	 *            要统计的天数
	 * @return
	 */
	@Override
	public StatisticsResponse getTalentStoreStatistics(Long userId, int statisticsType, int dayNumType) {
		StatisticsResponse statisticsResp = new StatisticsResponse();
		// 开始调访客统计
		if (StatisticsConstant.TYPE_VISITOR == statisticsType) {
			logger.info("---begin---访客统计---impl---");
			VisitorRecord visitorRecord = visitorRecordMapper.selectVisitorRecordByTalentId(userId);
			if (visitorRecord != null) {
				if (StatisticsConstant.DAY_NUMBER_7 == dayNumType) {
					statisticsResp.setVisitorNum(visitorRecord.getSevenGuest());
					statisticsResp.setClickNum(visitorRecord.getSevenBrowseRecord());
				} else if (StatisticsConstant.DAY_NUMBER_30 == dayNumType) {
					statisticsResp.setVisitorNum(visitorRecord.getThirtyGuest());
					statisticsResp.setClickNum(visitorRecord.getThirtyBrowseRecord());
				} else if (StatisticsConstant.DAY_NUMBER_90 == dayNumType) {
					statisticsResp.setVisitorNum(visitorRecord.getNinetyGuest());
					statisticsResp.setClickNum(visitorRecord.getNinetyBrowseRecord());
				}
			}
			logger.info("---end---访客统计---impl---");
			return statisticsResp;
		}


		// 开始调订单统计
		OrderReport orderReport = orderStatisticsMapper.selectTalentTeacherOrderReport(userId);
		if (orderReport == null) {
			orderReport = new OrderReport();
		}
		if (StatisticsConstant.TYPE_ORDER == statisticsType) {
			UserInfo userInfo = userInfoMapper.selectByUserId(userId);
			TalentOrderQuantityReport talentOrderQuantityReport = orderStatisticsMapper
					.selectTalentOrderNumByTeacherPersionId(userInfo.getPersionId());
			
			if (talentOrderQuantityReport == null) {
				talentOrderQuantityReport = new TalentOrderQuantityReport();
			}
			
			if (StatisticsConstant.DAY_NUMBER_7 == dayNumType) {
				statisticsResp.setTeacherOrderNum(orderReport.getSevenOrderQuantity());
				statisticsResp.setStudentOrderNum(talentOrderQuantityReport.getSevenPushQuantity());
			} else if (StatisticsConstant.DAY_NUMBER_30 == dayNumType) {
				statisticsResp.setTeacherOrderNum(orderReport.getThirtyOrderQuantity());
				statisticsResp.setStudentOrderNum(talentOrderQuantityReport.getThirtyPushQuantity());
			} else if (StatisticsConstant.DAY_NUMBER_90 == dayNumType) {
				statisticsResp.setTeacherOrderNum(orderReport.getNinetyOrderQuantity());
				statisticsResp.setStudentOrderNum(talentOrderQuantityReport.getNinetyPushQuantity());
			}
		}

		// 开始调营收统计
		if (StatisticsConstant.TYPE_SALES == statisticsType) {
			CommissionReport commissionReport = orderStatisticsMapper.selectCommissionReportByUserId(userId);
			SalesAmountReport salesAmountReport = orderStatisticsMapper.selectSalesAmountReportByUserId(userId);
			
			if (commissionReport == null) {
				commissionReport = new CommissionReport();
			}
			
			if (salesAmountReport == null) {
				salesAmountReport = new SalesAmountReport();
			}
			
			if (StatisticsConstant.DAY_NUMBER_7 == dayNumType) {
				statisticsResp.setSalesAmount(salesAmountReport.getSevenSalesAmount());
				statisticsResp.setCommission(commissionReport.getSevenHistoricalCommission());
			} else if (StatisticsConstant.DAY_NUMBER_30 == dayNumType) {
				statisticsResp.setSalesAmount(salesAmountReport.getThirtySalesAmount());
				statisticsResp.setCommission(commissionReport.getThirtyHistoricalCommission());
			} else if (StatisticsConstant.DAY_NUMBER_90 == dayNumType) {
				statisticsResp.setSalesAmount(salesAmountReport.getNinetySalesAmount());
				statisticsResp.setCommission(commissionReport.getNinetyHistoricalCommission());
			}
		}
		return statisticsResp;
	}

	/**
	 * B区店铺本月业绩（校妆APP3.5期需求）
	 * 
	 * @author 卫耀华
	 * @param userId
	 * @return
	 */
	@Override
	public ThisMonthAchievement getThisMonthAchievement(Long userId) {
		logger.info("---begin---getTalentStoreStatistics---impl---");
		ThisMonthAchievement thisMonthAchievement = new ThisMonthAchievement();
		
		// 当月非自营产品销售目标
		int falseSaleMonthTarget = baseRestrictionsMapper.selectMonthSelfSupportFalseTarget();
		// 当月自营产品销售目标
		int trueSaleMonthTarget = baseRestrictionsMapper.selectMonthSelfSupportTrueTarget();
		// 当月佣金目标
		int commissionTarget = baseRestrictionsMapper.selectMonthCommissionTarget();
		
		// 获取讲师单月的佣金
		int monthCommission = orderStatisticsMapper.selectTalentTeacherMonthCommission(userId);
		thisMonthAchievement.setCommision(monthCommission);
		thisMonthAchievement.setCommisionTarget(commissionTarget);
		// TODO step1:调用SQL去统计
		SalesMonthReport salesMonthReport = orderStatisticsMapper.selectSalesMonthReportByUserId(userId);
		
		if (salesMonthReport == null) {
			salesMonthReport = new SalesMonthReport();
		}
		
		thisMonthAchievement.setNoSelfSupportSales(salesMonthReport.getSelfSupportFalse());
		thisMonthAchievement.setNoSelfSupportSalesTarget(falseSaleMonthTarget);
		
		thisMonthAchievement.setSelfSupportSales(salesMonthReport.getSelfSupportTrue());
		thisMonthAchievement.setSelfSupportSalesTarget(trueSaleMonthTarget);
		thisMonthAchievement.setMoney(userMapper.selectUserMoney(userId));
		thisMonthAchievement.setLimitMoney(baseRestrictionsMapper.selectCommisionLimit());
		// TODO step2:将SQL统计结果set到返回对象中
		logger.info("---end---getTalentStoreStatistics---impl---");
		return thisMonthAchievement;
	}

	/**
	 * 本月业绩排名榜（校妆APP3.5期需求）
	 * 
	 * @author 卫耀华
	 * @param selfSupport
	 * @return
	 */
	@Override
	public List<SalesRanking> getThisMonthSalesRanking(int selfSupport) {
		logger.info("---begin---getThisMonthSalesRanking---impl---");
		// TODO 查询limit 50个讲师，并组装成list返回
		List<SalesRanking> salesRankingList = new ArrayList<SalesRanking>();
		// 自营
		if (selfSupport == 0) {
			salesRankingList = orderStatisticsMapper.selectSalesRankingSelfSupportTrue();
		}
		// 非自营
		if (selfSupport == 1) {
			salesRankingList = orderStatisticsMapper.selectSalesRankingSelfSupportFalse();
		}
		return salesRankingList;
	}

	@Override
	public List<TalentOrder> getTeacherOrderEntity(long userId, int type, int startIndex, int pageSize) {
		// TODO Auto-generated method stub
		UserInfo userInfo = userInfoMapper.selectByUserId(userId);
		
		int array[] = null;
		
		switch (type) {
		case 1: // 
			array = new int []{2,3,4,6,7};
			break;
		case 2:
			array = new int []{2};
			break;
		case 3:
			array = new int []{3};
			break;
		case 4:
			array = new int []{4};
			break;
		case 6:
			array = new int []{6};
			break;
		case 7:
			array = new int []{7};
			break;
		default:
			return new ArrayList<TalentOrder>();
		}
		
		List<TalentOrderEntity> resultList = orderStatisticsMapper.selectTalentOrderEntityByIdAndPersionId(userId, userInfo.getPersionId(), array, startIndex, pageSize);
		
		if (resultList == null) {
			return new ArrayList<TalentOrder>();
		}
		
		List<Long> orderInfoIdList = new ArrayList<Long>();
		
		for (TalentOrderEntity ids : resultList) {
			orderInfoIdList.add(ids.getOrderId());
		}
		orderInfoIdList = removeDuplicate(orderInfoIdList);
		
		List<TalentOrder> resModel = new ArrayList<TalentOrder>();
		
		for (Long orderInfoId : orderInfoIdList) {
			TalentOrder dealModel = new TalentOrder();
			dealModel.setOrderInfoId(orderInfoId);
			
			List<TalentOrderDetail> stepTwo = new ArrayList<TalentOrderDetail>();
			
			for (TalentOrderEntity talentOrderEntity : resultList) {
				if (talentOrderEntity.getOrderId() == orderInfoId) {
					dealModel.setCreateTime(talentOrderEntity.getCreateTime());
					dealModel.setStatus(talentOrderEntity.getInfoStatus());
					dealModel.setOrderSn(talentOrderEntity.getOrderSn());
					
					TalentOrderDetail stepThree = new TalentOrderDetail();
					stepThree.setCommission(talentOrderEntity.getCommission());
					stepThree.setGoodsName(talentOrderEntity.getGoodName());
					stepThree.setGoodsImage(talentOrderEntity.getGoodsImage());
					stepThree.setOrderDetailId(talentOrderEntity.getOrderDetailId());
					stepThree.setQuantity(talentOrderEntity.getQuantity());
					stepThree.setSpecName(talentOrderEntity.getSpecName());
					stepThree.setStatus(talentOrderEntity.getStatus());
					stepThree.setTotalFee(talentOrderEntity.getTotalFee());
					stepTwo.add(stepThree);
					// resultList.remove(talentOrderEntity);
				}
			}
			dealModel.setOrderDetailList(stepTwo);
			resModel.add(dealModel);
		}
		return resModel;
	}
	
	/**
	 * 去除集合中重复的元素并且保持原集合的顺序
	 * @param list
	 * @return
	 */
	public List<Long> removeDuplicate(List<Long> list) {
		Set<Long> set = new HashSet<Long>();
		List<Long> newList = new ArrayList<Long>();
		for (Iterator<Long> iter = list.iterator(); iter.hasNext();) {
			Long element = iter.next();
			if (set.add(element))
				newList.add(element);
		}
		return newList;
	}

	@Override
	public List<TalentStudent> getTeacherStudentEntity(Long userId, int startIndex, Integer pageSize) {
		// TODO Auto-generated method stub
		UserInfo userInfo = userInfoMapper.selectByUserId(userId);
		List<TalentStudent> resModel = orderStatisticsMapper.selectTalentStudentByTeacherPersionId(userInfo.getPersionId(),startIndex,pageSize);
		if (resModel == null) {
			resModel = new ArrayList<TalentStudent>();
		}
		return resModel;
	}

	@Override
	public Map<String,Object> selectOrderInfoIds(String persionId, StoreCenterRequest selectCondition, User user) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public StoreCenterOrderResponse selectOrderDetailByOrderInfoIds(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public ResponseWallet selectMyWallet(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TalentStudent> selectStoreLink(long userId, int orderBy) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public Long selectStoreNumber(long userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TalentStudent> selectStoreCenterStudents(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public RevenueResponse selectRevenueDetails(StoreCenterRequest selectCondition) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Long selectUnderStoreNumber(long userId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<TalentStudent> queryUnderStudent(Long userId, int orderBy) {
		return null;
	}

}
